package com.ruoyi.web.controller.data;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SystemType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.data.domain.DataScore;
import com.ruoyi.data.domain.DataScoreExchange;
import com.ruoyi.data.service.IDataScoreService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 积分记录Controller
 *
 * @author zzp
 * @date 2022-09-30
 */
@RestController
@RequestMapping("/data/score")
public class DataScoreController extends BaseController {

    @Autowired
    private IDataScoreService dataScoreService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询积分记录列表
     */
    @PreAuthorize("@ss.hasPermi('data:score:list')")
    @GetMapping("/list")
    public TableDataInfo list(DataScore dataScore) {
        startPage();
        List<DataScore> list = dataScoreService.selectDataScoreList(dataScore);
        return getDataTable(list);
    }

    /**
     * 导出积分记录列表
     */
    @PreAuthorize("@ss.hasPermi('data:score:export')")
    @Log(title = "积分记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DataScore dataScore) {
        List<DataScore> list = dataScoreService.selectDataScoreList(dataScore);
        ExcelUtil<DataScore> util = new ExcelUtil<DataScore>(DataScore.class);
        util.exportExcel(response, list, "积分记录数据");
    }

    /**
     * 获取积分记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('data:score:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(dataScoreService.selectDataScoreById(id));
    }

    /**
     * 新增积分记录
     */
    @PreAuthorize("@ss.hasPermi('data:score:add')")
    @Log(title = "积分记录", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody DataScore dataScore) {
        if (StringUtils.isNull(dataScore.getUserId())) {
            return AjaxResult.error("请选择用户");
        } else {
            SysUser user = userService.selectUserById(dataScore.getUserId());
            if (StringUtils.isNull(user)) {
                return AjaxResult.error("用户不存在");
            }
            if (dataScore.getScoreType().equals(SystemType.IN.getCode())) {
                user.setScoreAll(user.getScoreAll() + dataScore.getScore());
                user.setScoreAvailable(user.getScoreAvailable() + dataScore.getScore());
            } else {
                if (user.getScoreAvailable() < dataScore.getScore()) {
                    return AjaxResult.error("用户可用积分不足");
                }
                user.setScoreAvailable(user.getScoreAvailable() - dataScore.getScore());
                user.setScoreUse(user.getScoreUse() + dataScore.getScore());
            }
            userService.updateUserProfile(user);
            dataScore.setScoreCurrent(user.getScoreAvailable());
            dataScoreService.insertDataScore(dataScore);
            return AjaxResult.success();
        }
    }

    /**
     * 修改积分记录
     */
    @PreAuthorize("@ss.hasPermi('data:score:edit')")
    @Log(title = "积分记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DataScore dataScore) {
        return toAjax(dataScoreService.updateDataScore(dataScore));
    }

    /**
     * 删除积分记录
     */
    @PreAuthorize("@ss.hasPermi('data:score:remove')")
    @Log(title = "积分记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(dataScoreService.deleteDataScoreByIds(ids));
    }

    /**
     * 兑换积分列表
     */
    @PreAuthorize("@ss.hasPermi('data:score:list')")
    @GetMapping("/exchangeList")
    public TableDataInfo exchangeList(DataScore dataScore) {
        startPage();
        List<DataScore> list = dataScoreService.selectDataScoreExchangeList(dataScore);
        return getDataTable(list);
    }

    /**
     * 导出兑换积分列表
     */
    @PreAuthorize("@ss.hasPermi('data:score:export')")
    @Log(title = "积分记录", businessType = BusinessType.EXPORT)
    @PostMapping("/exportExchange")
    public void exportExchange(HttpServletResponse response, DataScore dataScore) {
        List<DataScoreExchange> list = dataScoreService.selectDataScoreExchangeListExport(dataScore);
        ExcelUtil<DataScoreExchange> util = new ExcelUtil<DataScoreExchange>(DataScoreExchange.class);
        util.exportExcel(response, list, "兑换积分列表");
    }

    /**
     * 选择兑换积分记录
     */
    @PreAuthorize("@ss.hasPermi('data:score:exchange')")
    @Log(title = "积分记录", businessType = BusinessType.UPDATE)
    @GetMapping("/exchange")
    public AjaxResult exchange(DataScore dataScore) {
        List<DataScore> list = dataScoreService.selectDataScoreExchangeList(dataScore);
        if (list.size() > 0) {
            List<DataScore> exchangeList = new ArrayList<>();
            DataScore exchange;
            SysUser user;
            for (DataScore item : list) {
                exchange = new DataScore();
                exchange.setId(null);
                exchange.setDeptId(item.getDeptId());
                exchange.setUserId(item.getUserId());
                exchange.setNickName(item.getNickName());
                exchange.setScore(item.getScore());
                exchange.setScoreCurrent(item.getScoreCurrent() - exchange.getScore());
                exchange.setScoreType("out");
                exchange.setScoreDesc("系统兑换了" + item.getScore() + "积分");
                exchange.setCreateBy(getUsername());
                exchange.setCreateTime(DateUtils.getNowDate());
                exchangeList.add(exchange);
                user = userService.selectUserById(item.getUserId());
                user.setScoreAvailable(user.getScoreAvailable() - item.getScore());
                user.setScoreUse(user.getScoreUse() + item.getScore());
                userService.updateUserProfile(user);
            }
            dataScoreService.batchInsert(exchangeList);
        }
        return AjaxResult.success();
    }
}
